<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="推荐人ID" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入推荐人ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="序号" prop="mark">
              <el-input v-model="queryParams.mark" placeholder="请输入用户序号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="钱包地址" prop="walletAddress">
              <el-input v-model="queryParams.walletAddress" placeholder="请输入钱包地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="推荐地址" prop="parentWalletAddress">
              <el-input v-model="queryParams.parentWalletAddress" placeholder="请输入推荐人钱包地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="级别" prop="userLevel">
              <el-select v-model="queryParams.userLevel" placeholder="请选择级别" clearable>
                <el-option v-for="dict in biz_user_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="节点级别" prop="nodeFlag">
              <el-select v-model="queryParams.nodeFlag" placeholder="节点级别" clearable>
                <el-option v-for="dict in biz_user_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="usdt提现权限" prop="hasUsdtWithdraw">
              <el-select v-model="queryParams.hasUsdtWithdraw" placeholder="请选择usdt提现权限" clearable >
                <el-option v-for="dict in biz_status_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="aleo提现权限" prop="hasAleoWithdraw">
              <el-select v-model="queryParams.hasAleoWithdraw" placeholder="请选择aleo提现权限" clearable >
                <el-option v-for="dict in biz_status_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item> -->
            <el-form-item label="新会员" prop="isNew">
              <el-select v-model="queryParams.isNew" placeholder="请选择是否新会员" clearable>
                <el-option v-for="dict in biz_status_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="激活状态" prop="isActive">
              <el-select v-model="queryParams.isActive" placeholder="请选择激活状态" clearable>
                <el-option v-for="dict in biz_status_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="帐号状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择帐号状态" clearable>
                <el-option v-for="dict in biz_status_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:user:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:user:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:user:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:user:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              class="upload-demo"
              action="http://testmannage.whaleminer.org/aleo/business/user/importData"
              :headers="{
                'Authorization': 'Bearer ' + getToken()
              }"
              :limit="1"
              :http-request="handleExportTo"
              :show-file-list="false"
            >
              <el-button v-hasPermi="['business:user:export']" type="warning" plain icon="Upload">导入</el-button>
            </el-upload>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="用户ID" align="center" prop="userId" />
        <el-table-column v-if="true" label="序号" align="center" prop="mark" />
        <el-table-column label="昵称" align="center" prop="userName" />
        <el-table-column label="钱包地址" align="center" prop="walletAddress" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center; cursor: pointer" @click="copy(scope.row.walletAddress)">
              {{ $filters.address(scope.row.walletAddress) }}
              <el-icon style="margin-left: 5px"><CopyDocument /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推荐人" align="center" prop="parentId" />
        <el-table-column label="推荐人钱包地址" align="center" prop="parentWalletAddress" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center; cursor: pointer" @click="copy(scope.row.parentWalletAddress)">
              {{ $filters.address(scope.row.parentWalletAddress) }}
              <el-icon style="margin-left: 5px"><CopyDocument /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="祖级列表" align="center" prop="ancestors" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center; cursor: pointer" @click="copy(scope.row.ancestors)">
              <div style="width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                {{ scope.row.ancestors }}
              </div>
              <el-icon style="margin-left: 5px"><CopyDocument /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="级别" align="center" prop="userLevel">
          <template #default="scope">
            <dict-tag :options="biz_user_level" :value="scope.row.userLevel" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="本人业绩" align="center" prop="selfAchievement" /> -->
        <el-table-column label="团队业绩" align="center" prop="teamAchievement" />
        <el-table-column label="个人业绩" align="center" prop="selfAchievement" />
        <el-table-column label="直推业绩" align="center" prop="directPushAchievement" />
        <el-table-column label="算力" align="center" prop="computility" />
        <el-table-column label="购买算力" align="center" prop="purchaseComputility" />
        <el-table-column label="usdt" align="center" prop="usdt" width="100" />
        <el-table-column label="aleo" align="center" prop="aleo" width="100" />
        <el-table-column label="scr" align="center" prop="scr" width="100" />
        <el-table-column label="szpn" align="center" prop="availableSzpn" width="100" />
        <el-table-column label="锁仓szpn" align="center" prop="freezeSzpn" width="100" />
        <el-table-column label="理财szpn" align="center" prop="financingSzpn" width="100" />
        <el-table-column label="划转szpn" align="center" prop="transferSzpn" width="100" />
        <el-table-column label="节点档位" align="center" prop="nodeFlag">
          <template #default="scope">
            <dict-tag :options="biz_user_level" :value="scope.row.nodeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="是否节点" align="center" prop="isNode" width="100" />

        <!-- <el-table-column label="直推入金列表" align="center" prop="directPushDeposit" /> -->
        <el-table-column label="usdt提现权限" align="center" prop="hasUsdtWithdraw" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasUsdtWithdraw" @change="update($event, scope.row, 'usdt')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="aleo提现权限" align="center" prop="hasAleoWithdraw" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasAleoWithdraw" @change="update($event, scope.row, 'aleo')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="scr提现权限" align="center" prop="hasScrWithdraw" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasScrWithdraw" @change="update($event, scope.row, 'scr')"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="szpn闪对划转szpn权限" align="center" prop="hasSzpnToTransferSzpn" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasSzpnToTransferSzpn" @change="update($event, scope.row, 'hasSzpnToTransferSzpn')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="转账权限" align="center" prop="hasTransfer" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasTransfer" @change="update($event, scope.row, 'hasTransfer')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="分红权限" align="center" prop="hasDividend" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasDividend" @change="update($event, scope.row, 'hasDividend')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="闪兑权限" align="center" prop="hasConvert" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.hasConvert" @change="update($event, scope.row, 'hasConvert')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否新会员" align="center" prop="isNew" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isNew" @change="update($event, scope.row, 'isNew')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="激活状态" align="center" prop="isActive">
          <template #default="scope">
            <el-switch v-model="scope.row.isActive" @change="update($event, scope.row, 'isActive')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="帐号状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="update($event, scope.row, 'status')"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="购买时间" align="center" prop="purchaseTime" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="划拨算力" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="dosetComputility(scope.row)">划拨算力</el-button>
            </el-tooltip>
            <el-tooltip content="人工空投" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="doairdropManual(scope.row)">人工空投</el-button>
            </el-tooltip>
            <el-tooltip content="社区扶持" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="docommunitySupport(scope.row)">社区扶持</el-button>
            </el-tooltip>
            <!-- <el-tooltip content="网体关系" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="toDiagram(scope.row)">网体关系</el-button>
            </el-tooltip> -->
            <el-tooltip content="重置密码" placement="top">
              <el-button v-hasPermi="['business:user:edit']" link type="primary" @click="handleUpdatePassword(scope.row)">重置密码</el-button>
            </el-tooltip>
            <el-tooltip content="修改资产" placement="top">
              <el-button v-hasPermi="['business:user:modifyAsset']" link type="primary" @click="handleModifyAsset(scope.row.userId)">修改资产</el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:user:remove']"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="昵称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="钱包地址" prop="walletAddress">
          <el-input v-model="form.walletAddress" placeholder="请输入钱包地址" />
        </el-form-item> -->
        <el-form-item label="推荐人" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入推荐人" />
        </el-form-item>
        <el-form-item label="推荐人钱包" prop="parentWalletAddress">
          <el-input v-model="form.parentWalletAddress" placeholder="请输入推荐人钱包地址" />
        </el-form-item>
        <el-form-item label="钱包地址" prop="walletAddress">
          <el-input v-model="form.walletAddress" placeholder="请输入钱包地址" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <!-- <el-input v-model="form.level" placeholder="请输入级别" /> -->
          <el-select v-model="form.userLevel" placeholder="请选择级别" clearable>
            <el-option v-for="dict in biz_user_level" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="节点档位" prop="nodeFlag">
          <!-- <el-input v-model="form.level" placeholder="请输入级别" /> -->
          <el-select v-model="form.nodeFlag" placeholder="请选择节点档位" clearable>
            <el-option v-for="dict in biz_user_level" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否节点" prop="isNode">
          <el-input v-model="form.isNode" placeholder="请输入true/false" />
        </el-form-item>
        <!-- <el-form-item label="本人业绩" prop="selfAchievement">
          <el-input v-model="form.selfAchievement" placeholder="请输入本人业绩" />
        </el-form-item>
        <el-form-item label="团队业绩" prop="teamAchievement">
          <el-input v-model="form.teamAchievement" placeholder="请输入团队业绩" />
        </el-form-item>
        <el-form-item label="直推业绩" prop="directPushAchievement">
          <el-input v-model="form.directPushAchievement" placeholder="请输入直推业绩" />
        </el-form-item> -->
        <el-form-item label="算力" prop="computility">
          <el-input v-model="form.computility" placeholder="请输入算力" />
        </el-form-item>
        <el-form-item label="个人业绩" prop="selfAchievement">
          <el-input v-model="form.selfAchievement" placeholder="请输入个人业绩" />
        </el-form-item>
        <el-form-item label="usdt" prop="usdt">
          <el-input v-model="form.usdt" placeholder="请输入usdt" />
        </el-form-item>
        <el-form-item label="aleo" prop="aleo">
          <el-input v-model="form.aleo" placeholder="请输入aleo" />
        </el-form-item>
        <el-form-item label="scr" prop="scr">
          <el-input v-model="form.scr" placeholder="请输入scr" />
        </el-form-item>
        <el-form-item label="szpn" prop="availableSzpn">
          <el-input v-model="form.availableSzpn" placeholder="请输入szpn" />
        </el-form-item>
        <el-form-item label="锁仓szpn" prop="freezeSzpn">
          <el-input v-model="form.freezeSzpn" placeholder="请输入锁仓szpn" />
        </el-form-item>
        <el-form-item label="理财szpn" prop="financingSzpn">
          <el-input v-model="form.financingSzpn" placeholder="请输入理财szpn" />
        </el-form-item>
        <el-form-item label="祖级列表" prop="ancestors">
          <el-input v-model="form.ancestors" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="twice.twiceAuthCodeDialogVisible" :width="500" title="二次认证">
      <div class="auth-area1">
        <div class="auth-tips1">输入登录密码</div>
        <div class="auth-input">
          <el-input
            v-model="twice.twiceAuthCode"
            auto-complete="off"
            placeholder="请输入输入登录密码"
            size="large"
            style="width: 100%"
            type="password"
          ></el-input>
        </div>
        <div class="auth-botton">
          <el-button size="large" style="width: 100%" type="primary" @click="twiceAuthSubmit">验证</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog v-model="passwordDialog.visible" :width="500" title="重置密码">
      <div class="auth-area1">
        <div class="auth-tips1">输入新密码</div>
        <div class="auth-input">
          <el-input
            v-model="passwordDialog.password"
            auto-complete="off"
            placeholder="请输入输入新密码"
            size="large"
            style="width: 100%"
            type="password"
          ></el-input>
        </div>
        <div class="auth-botton">
          <el-button size="large" style="width: 100%" type="primary" @click="passwordSubmit">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 人工空投 -->
    <el-dialog v-model="airdrop.visible" :title="airdrop.title" width="669px" append-to-body>
      <el-form ref="airdropRef" :model="airdropManualBo" label-width="120px">
        <el-form-item label="userId" prop="userId">
          <el-input v-model="airdropManualBo.userId" clearable placeholder="userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="转出或转入" prop="transferFlag">
          <el-select v-model="airdropManualBo.transferFlag" placeholder="请选择转出或转入" style="width: 100%">
            <el-option v-for="dict in biz_transfer_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="airdropManualBo.amount" clearable placeholder="金额"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="doairdropManualSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改资产对话框 -->
    <el-dialog v-model="modifyAssetDialog.visible" :title="modifyAssetDialog.title" width="500px" append-to-body>
      <el-form ref="modifyAssetFormRef" :model="modifyAssetForm" label-width="120px">
        <el-form-item label="资产类型" prop="assetType">
          <el-select v-model="modifyAssetForm.assetType" placeholder="请选择资产类型" clearable>
            <el-option v-for="dict in biz_found_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="修改类型" prop="transferFlag">
          <el-select v-model="modifyAssetForm.transferFlag" placeholder="请选择修改类型" clearable>
            <el-option v-for="dict in biz_transfer_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="modifyAssetForm.amount" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelModifyAsset">取消</el-button>
          <el-button type="primary" @click="submitModifyAsset">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User" lang="ts">
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  setComputility,
  airdropManual,
  communitySupport,
  importData,
  openSafe,
  modifyAsset
} from '@/api/business/user';
import { UserVO, UserQuery, UserForm } from '@/api/business/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { biz_status_type, biz_user_type, biz_user_level, biz_transfer_flag, biz_found_type } = toRefs<any>(
  proxy?.useDict('biz_status_type', 'biz_user_type', 'biz_user_level', 'biz_transfer_flag', 'biz_found_type')
);
import { getToken } from '@/utils/auth';
import useClipboard from 'vue-clipboard3';
/** 数据初始化定义 */
const { toClipboard } = useClipboard();

const userList = ref<UserVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();
const airdropRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const airdrop = reactive<DialogOption>({
  visible: false,
  title: '人工空投'
});

const modifyAssetDialog = reactive({
  visible: false,
  title: '修改资产',
  userId: null
});

const modifyAssetForm = reactive({
  transferFlag: undefined,
  assetType: undefined,
  amount: undefined
});

const modifyAssetFormRef = ref<ElFormInstance>();

const handleModifyAsset = (userId) => {
  modifyAssetDialog.userId = userId;
  modifyAssetDialog.visible = true;
};

const cancelModifyAsset = () => {
  modifyAssetDialog.visible = false;
  modifyAssetFormRef.value?.resetFields();
};

const submitModifyAsset = () => {
  reset();
  modifyAssetFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 调用 modifyAsset 接口
      const payload = {
        userId: modifyAssetDialog.userId,
        transferFlag: modifyAssetForm.transferFlag,
        assetType: modifyAssetForm.assetType,
        amount: modifyAssetForm.amount
      };
      console.log('修改资产数据:', payload);
      await modifyAsset(payload).then(() => {
        proxy?.$modal.msgSuccess('资产修改成功');
        modifyAssetDialog.visible = false;
      });
      await getList();
    }
  });
};

const initFormData: UserForm = {
  userId: undefined,
  userName: undefined,
  walletAddress: undefined,
  parentId: undefined,
  parentWalletAddress: undefined,
  userLevel: undefined,
  nodeFlag: undefined,
  isNode: undefined,
  selfAchievement: undefined,
  teamAchievement: undefined,
  directPushAchievement: undefined,
  computility: undefined,
  usdt: undefined,
  aleo: undefined,
  ancestors: undefined,
  directPushDeposit: undefined,
  hasUsdtWithdraw: undefined,
  hasAleoWithdraw: undefined,
  isNew: undefined,
  isActive: undefined,
  status: undefined,
  password: undefined
};
const data = reactive<PageData<UserForm, UserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    mark: undefined,
    userName: undefined,
    walletAddress: undefined,
    parentId: undefined,
    parentWalletAddress: undefined,
    userLevel: undefined,
    nodeFlag: undefined,
    isNode: undefined,
    selfAchievement: undefined,
    teamAchievement: undefined,
    directPushAchievement: undefined,
    computility: undefined,
    usdt: undefined,
    aleo: undefined,
    ancestors: undefined,
    directPushDeposit: undefined,
    hasUsdtWithdraw: undefined,
    hasAleoWithdraw: undefined,
    isNew: undefined,
    isActive: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    userName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
    walletAddress: [{ required: true, message: '钱包地址不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '推荐人不能为空', trigger: 'blur' }],
    parentWalletAddress: [{ required: true, message: '推荐人钱包地址不能为空', trigger: 'blur' }],
    userLevel: [{ required: true, message: '级别不能为空', trigger: 'blur' }],
    selfAchievement: [{ required: true, message: '本人业绩不能为空', trigger: 'blur' }],
    teamAchievement: [{ required: true, message: '团队业绩不能为空', trigger: 'blur' }],
    directPushAchievement: [{ required: true, message: '直推业绩不能为空', trigger: 'blur' }],
    computility: [{ required: true, message: '算力不能为空', trigger: 'blur' }],
    usdt: [{ required: true, message: 'usdt不能为空', trigger: 'blur' }],
    aleo: [{ required: true, message: 'aleo不能为空', trigger: 'blur' }],
    ancestors: [{ required: true, message: '祖级列表不能为空', trigger: 'blur' }],
    directPushDeposit: [{ required: true, message: '直推入金列表不能为空', trigger: 'blur' }],
    hasUsdtWithdraw: [{ required: true, message: 'usdt提现权限不能为空', trigger: 'change' }],
    hasAleoWithdraw: [{ required: true, message: 'aleo提现权限不能为空', trigger: 'change' }],
    isNew: [{ required: true, message: '是否新会员不能为空', trigger: 'change' }],
    isActive: [{ required: true, message: '激活状态不能为空', trigger: 'change' }],
    status: [{ required: true, message: '帐号状态不能为空', trigger: 'change' }]
  },
  twice: {
    twiceAuthCodeDialogVisible: false,
    twiceAuthCode: null
  }
});

const { queryParams, form, rules, twice } = toRefs(data);

/** 查询用户信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUser(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  airdrop.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
  airdropRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加用户信息';
};

const airdropManualBo = reactive<DialogOption>({
  userId: undefined,
  transferFlag: undefined,
  amount: undefined
});

const passwordDialog = reactive<DialogOption>({
  visible: false,
  title: '',
  password: null
});

/** 修改按钮操作 */
const handleUpdate = async (row?: UserVO) => {
  reset();
  const _userId = row?.userId || ids.value[0];
  const res = await getUser(_userId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改用户信息';
};

/** 修改密码操作 */
const handleUpdatePassword = async (row?: UserVO) => {
  reset();
  const _userId = row?.userId || ids.value[0];
  const res = await getUser(_userId);
  Object.assign(form.value, res.data);
  passwordDialog.visible = true;
  passwordDialog.title = '重置密码';
};

const passwordSubmit = () => {
  updateUser({
    userId: form.value.userId,
    password: passwordDialog.password
  })
    .then((res) => {
      passwordDialog.password = null;
      if (res.code == 200) {
        if (res.msg == '0') {
          // 二次验证弹框
          twice.value.twiceAuthCodeDialogVisible = true;
        }
      }
    })
    .finally(() => (passwordDialog.visible = false));
};

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.userId) {
        await updateUser({
          userId: form.value.userId,
          walletAddress: form.value.walletAddress,
          parentId: form.value.parentId,
          parentWalletAddress: form.value.parentWalletAddress,
          userLevel: form.value.userLevel,
          nodeFlag: form.value.nodeFlag,
          isNode: form.value.isNode,
          computility: form.value.computility,
          selfAchievement: form.value.selfAchievement,
          usdt: form.value.usdt,
          aleo: form.value.aleo,
          ancestors: form.value.ancestors
          // password: form.value.password
        })
          .then((res) => {
            if (res.code == 200) {
              if (res.msg == '0') {
                // 二次验证弹框
                twice.value.twiceAuthCodeDialogVisible = true;
              }
            }
          })
          .finally(() => (buttonLoading.value = false));
      } else {
        await addUser(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户信息编号为"' + _userIds + '"的数据项？').finally(() => (loading.value = false));
  await delUser(_userIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/user/export',
    {
      ...queryParams.value
    },
    `user_${new Date().getTime()}.xlsx`
  );
};
/** 导入按钮操作 */
const handleExportTo = (item) => {
  const formData = new FormData();
  formData.append('file', item.file); // file是你要上传的文件对象
  importData(formData).then(async (res) => {
    proxy?.$modal.msgSuccess(res.msg);
    await getList();
  });
};

// 修改
const update = async (val: boolean, row?: UserVO, type: string) => {
  buttonLoading.value = true;
  let form = {};
  switch (type) {
    case 'usdt':
      form = {
        userId: row?.userId,
        hasUsdtWithdraw: val
      };
      break;
    case 'aleo':
      form = {
        userId: row?.userId,
        hasAleoWithdraw: val
      };
      break;
    case 'scr':
      form = {
        userId: row?.userId,
        hasScrWithdraw: val
      };
      break;

    case 'hasSzpnToTransferSzpn':
      form = {
        userId: row?.userId,
        hasSzpnToTransferSzpn: val
      };
      break;
    case 'hasTransfer':
      form = {
        userId: row?.userId,
        hasTransfer: val
      };
      break;
    case 'isActive':
      form = {
        userId: row?.userId,
        isActive: val
      };
      break;
    case 'status':
      form = {
        userId: row?.userId,
        status: val
      };
      break;
    case 'isNew':
      form = {
        userId: row?.userId,
        isNew: val
      };
      break;
    case 'hasDividend':
      form = {
        userId: row?.userId,
        hasDividend: val
      };
      break;
    case 'hasConvert':
      form = {
        userId: row?.userId,
        hasConvert: val
      };
      break;
  }
  await updateUser(form)
    .then((res) => {
      if (res.code == 200) {
        if (res.msg == '0') {
          // 二次验证弹框
          twice.value.twiceAuthCodeDialogVisible = true;
        } else {
          getList();
        }
      }
    })
    .finally(() => (buttonLoading.value = false));
};

// 划拨算力
const dosetComputility = (row: any) => {
  console.log(row);
  ElMessageBox.prompt('是否确认划拨算力?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(({ value }) => {
      setComputility({
        userId: row.userId,
        amount: value
      }).then((res) => {
        // console.log(res)
        if (res.code == 200) {
          if (res.msg == '0') {
            // 二次验证弹框
            twice.value.twiceAuthCodeDialogVisible = true;
          } else {
            getList();
          }
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};

// 人工空投
const doairdropManual = async (row?: UserVO) => {
  console.log(row);
  // airdrop.visible = true;

  // airdropManualBo.value.userId = row.userId;
  // airdropManualBo.value.amount = row.amount;
  // airdropManualBo.value.transferFlag = row.transferFlag;

  /* airdropManual({
    userId: airdropManualBo.userId,
    amount: airdropManualBo.amount,
    transferFlag: airdropManualBo.transferFlag
  }).then(res => {
       if (res.code == 200) {
         getList();
          // if (res.msg == '0') {
          //   // 二次验证弹框
          //   twice.value.twiceAuthCodeDialogVisible = true;
          // } else {
          //   getList();
          // }
        }
  }) */

  ElMessageBox.prompt('确认人工空投?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(({ value }) => {
      airdropManual({
        userId: row.userId,
        amount: value
      }).then((res) => {
        // console.log(res)
        if (res.code == 200) {
          if (res.msg == '0') {
            // 二次验证弹框
            twice.value.twiceAuthCodeDialogVisible = true;
          } else {
            getList();
          }
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};

// 社区扶持
const docommunitySupport = (row: any) => {
  console.log(row);
  ElMessageBox.prompt('确认社区扶持?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(({ value }) => {
      communitySupport({
        userId: row.userId,
        amount: value
      }).then((res) => {
        // console.log(res)
        if (res.code == 200) {
          if (res.msg == '0') {
            // 二次验证弹框
            twice.value.twiceAuthCodeDialogVisible = true;
          } else {
            getList();
          }
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};

const toDiagram = (row: any) => {
  proxy?.$router.push('/bizuser/business/diagram/index?id=' + row.userId);
};

const copy = async (address: any) => {
  // navigator.clipboard.writeText(address);
  // 如果clipboard API失败，可以回退到使用document.execCommand()方法
  try {
    await navigator.clipboard.writeText(address);
    ElMessage.success('复制成功');
  } catch (err) {
    console.error('复制失败', err);
    // 如果clipboard API失败，可以回退到使用document.execCommand()方法
    copyContent2(address);
  }
};

// 复制文本内容方法二
const copyContent2 = (text: any) => {
  // 复制结果
  let copyResult = true;
  // 创建一个input元素
  let inputDom = document.createElement('textarea');
  // 设置为只读 防止移动端手机上弹出软键盘
  inputDom.setAttribute('readonly', 'readonly');
  // 给input元素赋值
  inputDom.value = text;
  // 将创建的input添加到body
  document.body.appendChild(inputDom);
  // 选中input元素的内容
  inputDom.select();
  // 执行浏览器复制命令
  // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签中的内容）
  // Input要在正常的编辑状态下原生复制方法才会生效
  const result = document.execCommand('copy');
  // 判断是否复制成功
  if (result) {
    ElMessage.success('复制成功');
  } else {
    console.log('复制失败');
    copyResult = false;
  }
  // 复制操作后再将构造的标签 移除
  document.body.removeChild(inputDom);
  // 返回复制操作的最终结果
  return copyResult;
};
// 二次认证
const twiceAuthSubmit = () => {
  openSafe({
    password: twice.value.twiceAuthCode
  }).then((res) => {
    ElMessage.success('认证成功，2分钟内免输密码');
    twice.value.twiceAuthCode = null;
    twice.value.twiceAuthCodeDialogVisible = false;
  });
};
onMounted(() => {
  getList();
});
</script>

<style>
.auth-area1 {
  padding-left: 45px;
  padding-right: 45px;
  padding-top: 30px;
  padding-bottom: 30px;
}

.auth-tittle {
  font-size: 16px;
  margin-bottom: 16px;
}

.auth-code {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.auth-tips {
  margin-top: 16px;
  color: #777;
}

.auth-tips1 {
  margin-bottom: 16px;
  color: #a0cfff;
  font-size: 18px;
  text-align: center;
}

.auth-tips2 {
  margin-top: 26px;
  color: #79bbff;
  font-size: 12px;
  text-align: left;
}

.auth-tips-red {
  margin-top: 6px;
  color: #53a8ff;
}

.auth-input {
  width: 100%;
  margin-top: 26px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;
}

.auth-botton {
  width: 100%;
  margin-top: 26px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;
}
</style>
